package initialize

import (
	"fmt"
	"go.opentelemetry.io/contrib/instrumentation/google.golang.org/grpc/otelgrpc"
	"go.uber.org/zap"
	"google.golang.org/grpc"
	"google.golang.org/grpc/credentials/insecure"
	"mxshop-api/order-web/global"
	"mxshop-api/order-web/proto"
	_ "mxshop-api/order-web/utils/grpc-consul-resolver" // It's important
)

func InitSrvConn() {
	consulInfo := global.ServerConfig.ConsulInfo
	orderConn, err := grpc.Dial(
		fmt.Sprintf("consul://%s:%d/%s?wait=14s&token=9bed74e4-1748-b21f-e871-2fca2dfabc5e", consulInfo.Host, consulInfo.Port, global.ServerConfig.OrderSrvInfo.Name),
		grpc.WithTransportCredentials(insecure.NewCredentials()),
		grpc.WithDefaultServiceConfig(`{"loadBalancingPolicy": "round_robin"}`), // 轮询访问
		grpc.WithUnaryInterceptor(otelgrpc.UnaryClientInterceptor()),            // 拦截普通的一次请求一次响应的rpc服务
		//grpc.WithStreamInterceptor(otelgrpc.StreamClientInterceptor()),          // 拦截流式的rpc服务
	)
	if err != nil {
		zap.S().Fatalf("[order-web] 连接 【订单服务】 失败")
	}
	global.OrderSrvClient = proto.NewOrderClient(orderConn)

	goodsConn, err := grpc.Dial(
		fmt.Sprintf("consul://%s:%d/%s?wait=14s&token=9bed74e4-1748-b21f-e871-2fca2dfabc5e", consulInfo.Host, consulInfo.Port, global.ServerConfig.GoodsSrvInfo.Name),
		grpc.WithTransportCredentials(insecure.NewCredentials()),
		grpc.WithDefaultServiceConfig(`{"loadBalancingPolicy": "round_robin"}`), // 轮询访问
		grpc.WithUnaryInterceptor(otelgrpc.UnaryClientInterceptor()),            // 拦截普通的一次请求一次响应的rpc服务
		//grpc.WithStreamInterceptor(otelgrpc.StreamClientInterceptor()),          // 拦截流式的rpc服务
	)
	if err != nil {
		zap.S().Fatalf("[goods-web] 连接 【商品服务】 失败")
	}
	global.GoodsSrvClient = proto.NewGoodsClient(goodsConn)

	inventoryConn, err := grpc.Dial(
		fmt.Sprintf("consul://%s:%d/%s?wait=14s&token=9bed74e4-1748-b21f-e871-2fca2dfabc5e", consulInfo.Host, consulInfo.Port, global.ServerConfig.InventorySrvInfo.Name),
		grpc.WithTransportCredentials(insecure.NewCredentials()),
		grpc.WithDefaultServiceConfig(`{"loadBalancingPolicy": "round_robin"}`), // 轮询访问
		grpc.WithUnaryInterceptor(otelgrpc.UnaryClientInterceptor()),            // 拦截普通的一次请求一次响应的rpc服务
		//grpc.WithStreamInterceptor(otelgrpc.StreamClientInterceptor()),          // 拦截流式的rpc服务
	)
	if err != nil {
		zap.S().Fatalf("[inventory-web] 连接 【库存服务】 失败")
	}
	global.InventorySrvClient = proto.NewInventoryClient(inventoryConn)
}
